package servers;

import java.io.BufferedReader;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;

/**
 * Servlet implementation class SocketServer
 */
@WebServlet("/socketServer")
public class SocketServer extends HttpServlet {
	private static final long serialVersionUID = 1L;
	InputStream is;
	OutputStream os;
	BufferedReader br;
	PrintWriter pw;
	private boolean isStart = false;
	ServerSocket serverSocket;
	List<PrintWriter> pwList = new ArrayList<PrintWriter>();
	List<String> msgList = new ArrayList<String>();
	List<String> infoList = new ArrayList<String>();
	HashMap<String, List<String>> map = new HashMap<String, List<String>>();
	
	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public SocketServer() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		//开启线程等待客户端连接
		new Thread(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				boolean isStop = false;
				try {
					if(!isStart) {
						serverSocket = new ServerSocket(9999);
						isStart = true;
					}
					Socket socket = serverSocket.accept();
					os = socket.getOutputStream();
					pw = new PrintWriter(new OutputStreamWriter(os));
		    		pwList.add(pw);
					//获取请求内容
				    String content;
				    while(!isStop) {
				    	is = socket.getInputStream();
				    	br = new BufferedReader(new InputStreamReader(is));
				    	if((content = br.readLine()) != null) {
				    		String[] arr = content.split("&");
				    		if("info".equals(arr[0])) {
				    			infoList.add(arr[1]);
				    			map.put("info", infoList);
				    			if("lhn:退出群聊".equals(arr[1])) {
				    				pwList.remove(pw);
						    		isStop = true;
						    	}
				    		}else {
				    			msgList.add(arr[1]);
				    			map.put("msg", msgList);
				    		}
				    		for(PrintWriter pws : pwList) {
				    			pws.println(JSON.toJSONString(map));
				    			pws.flush();
				    		}
				    	}
				    }
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} finally {
					//关闭资源
					//socket.shutdownInput();
					//pw.close();
		            //br.close();
		            //socket.close();
		            //serverSocket.close();
				}
			}
		}).start();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}
}
